﻿#region Usings

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.Caching;
using Castle.MonoRail.Framework;
using Rodunu.Movies.Contracts;
using Rodunu.Movies.Interfaces.Activity;
using Rodunu.Movies.Interfaces.Collections;
using Rodunu.Movies.Interfaces.Comments;
using Rodunu.Movies.Interfaces.Movie;
using Rodunu.Movies.Interfaces.Subscriptions;
using Rodunu.Movies.Interfaces.User;
using Rodunu.Movies.Logic.Activity;
using Rodunu.Movies.Logic.Collections;
using Rodunu.Movies.Logic.Comments;
using Rodunu.Movies.Logic.Movie;
using Rodunu.Movies.Logic.Subscriptions;
using Rodunu.Movies.Logic.User;
using Rodunu.Movies.Services.Amazon;
using Rodunu.Movies.Services.Interfaces;
using Rodunu.Movies.Services.Interfaces.Netflix;
using Rodunu.Movies.Services.Models.Movies;
using Rodunu.Movies.Services.Models.Netflix;
using Rodunu.Movies.Services.NetFlix.DataProvider.Logic;
using Rodunu.Movies.Services.NetFlix.DataProvider.NFService;
using Rodunu.Movies.Services.NetFlix.Logic;
using Rodunu.Movies.Web.Utility;
using Rodunu.Utilities.Import;
using Rodunu.Utilities.JSON;
using System.Linq;
using Movie=Rodunu.Movies.Contracts.Movie;

#endregion

namespace Rodunu.Movies.Web.Controllers
{
    public class MovieController : UserBaseController
    {
        #region Private Members

        private readonly IMovie _movieLogic;
        private readonly IUserMovies _userMoviesLogic;
        private readonly IUserCollections _userCollectionsLogic;
        private readonly IMovieTypes _movieTypesLogic;
        private readonly IUser _userLogic;
        private IServicesMovieLink _servicesMovieLinkLogic;
        private readonly IUserActivity _userActivityLogic;
        private readonly ICondition _userConditionLogic;
        private readonly IUserMoviesStatus _userMoviesStatusLogic;

        #endregion
        
        #region Constructor

        public MovieController()
        {
            _movieLogic = new MovieLogic();
            _userMoviesLogic = new UserMoviesLogic();
            _userCollectionsLogic = new UserCollectionsLogic();
            _movieTypesLogic = new MovieTypesLogic();
            _userLogic = new UserLogic();
            _userActivityLogic = new UserActivityLogic();
            _userConditionLogic = new ConditionLogic();
            _userMoviesStatusLogic = new UserMoviesStatusLogic();
        }

        #endregion

        #region Add

        public void Add(string s, string e)
        {
            SetUser();
            SetPage(PageTypes.AddMovie);
            SetLayout(true);

            PropertyBag["UserCollections"] = _userCollectionsLogic.GetUserCollectionsByUser(User.Id);
            PropertyBag["MovieType"] = _movieTypesLogic.FindAll();
            PropertyBag["Conditions"] = _userConditionLogic.FindAll();
            
            
            if (!string.IsNullOrEmpty(s))
            {
                if (!string.IsNullOrEmpty(e))
                {
                    PropertyBag["Saved"] = "There was an error while saving " + HttpUtility.UrlDecode(s);
                }
                else
                {
                    PropertyBag["Saved"] = HttpUtility.UrlDecode(s) + " was saved successfully!";
                }
            }
        }

        public void AddSave([DataBind("movie")] Movie movie, [DataBind("userMovies")] UserMovies userMovies, 
                            [DataBind("userCollections")] UserCollections userCollections, [DataBind("movieTypes")] MovieTypes movieTypes,
                            [DataBind("userCondition")] Condition userCondition)
        {
            SetUser();
            UserInfo userInfo = _userLogic.Find(User.Id);
            
            var newUserMovies = new UserMovies();

            //Need to do find by name
            newUserMovies.Movie = movie.Id > 0 ? _movieLogic.Find(movie.Id) : null;
            newUserMovies.UserInfo = userInfo;

            newUserMovies.UserCollections = _userCollectionsLogic.Find(userCollections.Id);
            newUserMovies.MovieTypes = _movieTypesLogic.Find(userMovies.MovieTypes.Id);
            newUserMovies.Condition = _userConditionLogic.Find(userCondition.Id);
            newUserMovies.UserMoviesStatus = _userMoviesStatusLogic.Find(1);

            var query = new NameValueCollection();
            try
            {
                newUserMovies.Id = 0;
                newUserMovies.LastModified = DateTime.Now;
                newUserMovies.LastModifiedBy = userInfo;
                newUserMovies.DateAdded = DateTime.Now;
                newUserMovies.DateAddedBy = userInfo;
                newUserMovies.AdditionalInfo = string.Empty;
                newUserMovies.Location = userMovies.Location;
                newUserMovies.Viewed = userMovies.Viewed;
                newUserMovies.Name = userMovies.Name;
                if (!string.IsNullOrEmpty(userMovies.Notes))
                    newUserMovies.Notes = userMovies.Notes;
                else
                    newUserMovies.Notes = string.Empty;

                _userMoviesLogic.Create(newUserMovies);
            }
            catch (Exception ex)
            {
                RenderText("0:::" + ex.Message);
                return;
                //query.Add("e", System.Web.HttpUtility.UrlEncode(ex.Message));
            }

            _userActivityLogic.Create(new UserActivity(userInfo, "Adding Movie", DateTime.Now, (int)UserActivityTypes.AddMovie, newUserMovies.Id));

            RenderText(newUserMovies.Id + ":::" + newUserMovies.Name);
        }

        public void AddChildrenToCollection(long userMovieId, string childrenMovies)
        {
            SetUser();
            IUserMovies userMoviesLogic = new UserMoviesLogic();
            string[] childMovies = childrenMovies.Split(',');
            UserMovies userMovieParent = userMoviesLogic.Find(userMovieId);
            

            if (userMovieParent != null)
            {
                userMovieParent = null;
                userMoviesLogic = null;
                try
                {
                    foreach (string s in childMovies)
                    {
                        if (!string.IsNullOrEmpty(s))
                        {
                            userMoviesLogic = new UserMoviesLogic();
                            UserMovies userMovie = userMoviesLogic.Find(Convert.ToInt64(s));
                            if (userMovie != null)
                            {
                                if (userMovie.Id != userMovieId)
                                {
                                    userMovie.ParentId = userMovieId;
                                    userMovie.FriendMovieRequests = new List<FriendMovieRequest>();
                                    _userMoviesLogic.Update(userMovie);
                                }
                            }
                        }
                    }
                    userMoviesLogic = null;
                    IUserMovies userMoviesLogic2 = new UserMoviesLogic();
                    UserMovies userMovieParent2 = userMoviesLogic2.Find(userMovieId);
                    userMovieParent2.IsCollection = true;
                    userMovieParent2.FriendMovieRequests = new List<FriendMovieRequest>();
                    userMoviesLogic2.Update(userMovieParent2);
                    Redirect("Movie", "UserMovies");
                    RenderText("Movies added to collection successfully.");
                }
                catch (Exception ex)
                {
                    RenderText(ex.Message);
                }
            }
            else
            {
                RenderText("The specified collection was not found.");
            }
            
        }

        #endregion

        #region Netflix

        public void MyNetflixQueue(int startIndex, int userId)
        {
            SetUser();
            SetPage(PageTypes.Movies);
            SetLayout(true);

            UserInfo userInfo = userId > 0 ? _userLogic.Find(userId) : _userLogic.Find(User.Id);

            IManageAtHome manageAtHome = new ManageAtHome(userInfo);
            PropertyBag["AtHome"] = manageAtHome.GetMoviesAtHome(0);

            IManageQueue manageQueue = new ManageQueue(userInfo);
            
            Queue queue = manageQueue.GetUserQueue(0, 500);
            PropertyBag["Queue"] = queue;
            PropertyBag["CurrentUser"] = User.Id;
            PropertyBag["ViewingUser"] = userId <= 0 ? User.Id : userId;
            if (userId <= 0 || userId == User.Id)
                PropertyBag["UserName"] = "Your";
            else
                PropertyBag["UserName"] = userInfo.Name + "'s";
        }

        public void NetflixDetail(long id, long userId, long movieId)
        {
            SetUser();
            SetPage(PageTypes.Movies);
            SetLayout(true);

            UserInfo user = _userLogic.Find(User.Id);

            PropertyBag["CurrentUser"] = User.Id;
            PropertyBag["IsAdmin"] = User.IsAdmin;

            if (id > 0)
            {
                UserMovies userMovies = _userMoviesLogic.Find(id);
                PropertyBag["UserMovie"] = userMovies;
                PropertyBag["ViewingUser"] = userId <= 0 ? User.Id : userId;

                if (userMovies.Movie != null && !string.IsNullOrEmpty(userMovies.Movie.NetflixId))
                {
                    IManageTitle manageTitle = new ManageTitle(user);
                    CatalogTitle catalogTitle = manageTitle.GetTitle(userMovies.Movie.NetflixId);
                    PropertyBag["CatalogTitle"] = catalogTitle;

                    PropertyBag["FormatAvailibility"] = manageTitle.GetFormatAvailibility(catalogTitle.Formats.Href);
                    PropertyBag["TitleStates"] = manageTitle.GetTitleStates(catalogTitle.TitleRef);

                    try
                    {
                        if (catalogTitle.Similars != null && catalogTitle.Similars.Href != null)
                            PropertyBag["Similars"] = manageTitle.GetSimilars(catalogTitle.Similars.Href, 0, 10);
                        if (catalogTitle.Series != null && catalogTitle.Series.Href != null)
                            PropertyBag["Series"] = manageTitle.GetSeries(catalogTitle.Series.Href, 0, 10);
                        if (catalogTitle.Episodes != null && catalogTitle.Episodes.Href != null)
                            PropertyBag["Episodes"] = manageTitle.GetEpisodes(catalogTitle.Episodes.Href, 0, 10);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            else if (movieId > 0)
            {
                Movie movie = _movieLogic.Find(movieId);
                PropertyBag["Movie"] = movie;
                PropertyBag["ViewingUser"] = User.Id;

                if (movie != null && !string.IsNullOrEmpty(movie.NetflixId))
                {
                    IManageTitle manageTitle = new ManageTitle(user);
                    CatalogTitle catalogTitle = manageTitle.GetTitle(movie.NetflixId);
                    PropertyBag["CatalogTitle"] = catalogTitle;

                    PropertyBag["FormatAvailibility"] = manageTitle.GetFormatAvailibility(catalogTitle.Formats.Href);

                    try
                    {
                        if (catalogTitle.Similars != null && catalogTitle.Similars.Href != null)
                            PropertyBag["Similars"] = manageTitle.GetSimilars(catalogTitle.Similars.Href, 0, 10);
                        if (catalogTitle.Series != null && catalogTitle.Series.Href != null)
                            PropertyBag["Series"] = manageTitle.GetSeries(catalogTitle.Series.Href, 0, 10);
                        if (catalogTitle.Episodes != null && catalogTitle.Episodes.Href != null)
                            PropertyBag["Episodes"] = manageTitle.GetEpisodes(catalogTitle.Episodes.Href, 0, 10);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }

        #endregion
        
        #region All Movies

        public void AllMovies()
        {
            SetUser();
            SetPage(PageTypes.Movies);
            SetLayout(true);
            PropertyBag["movies"] = _movieLogic.FindAll();
        }

        public void AllMoviesJson(string q)
        {
            SetUser();
            IList<Movie> movies;
            Cache cache = new Cache();
            if (cache["Movies" + q] != null)
            {
                movies = (IList<Movie>) cache["Movies" + q];
            }
            else
            {
                movies = _movieLogic.GetMoviesByLetters(q);
                cache.Add("Movies" + q, movies, null, DateTime.Now.AddDays(1), new TimeSpan(), CacheItemPriority.High,
                          null);
            }

            //RenderText(@"{""results"":" + JavaScriptConvert.SerializeObject(movies) + "}");
            
            var movieString = new StringBuilder();
            if (movies != null)
            {
                bool first = true;
                //movieString.Append("{");
                foreach (Movie movie in movies)
                {
                    if (!first)
                        movieString.Append(Environment.NewLine);
                    else
                        first = false;
                    movieString.Append(movie.Name);
                }
                //movieString.Append("}");
            }
            RenderText(movieString.ToString());
        }

        public void UserMoviesJson(string q)
        {
            SetUser();
            IList<UserMovies> movies = _userMoviesLogic.GetMoviesByLetters(q, User.Id);
            //Cache caching = new Cache();
            //if (caching["UserMovies" + q] != null)
            //{
            //    movies = (IList<UserMovies>)caching["UserMovies" + q];
            //}
            //else
            //{
            //    movies = _userMoviesLogic.GetMoviesByLetters(q);
            //    caching.Add("UserMovies" + q, movies, null, DateTime.Now.AddDays(1), new TimeSpan(), CacheItemPriority.High,
            //              null);
            //}

            var movieString = new StringBuilder();
            if (movies != null)
            {
                bool first = true;
                //movieString.Append("{");
                foreach (UserMovies movie in movies)
                {
                    if (!first)
                        movieString.Append(Environment.NewLine);
                    else
                        first = false;
                    movieString.Append(movie.Name);
                }
                //movieString.Append("}");
            }
            RenderText(movieString.ToString()); 
        }
        
        public void UserMovies(long id, long? collectionId, int? mediaTypeId, bool? viewed, int? userMoviesStatusId, int? conditionId, int? Favorites, long? movieId)
        {
            BuildMoviePage(id, movieId);

            if (Favorites != null && Favorites > 0)
                PropertyBag["userMovies"] = _userMoviesLogic.GetFavorites(id <= 0 ? User.Id : id);
            else
                PropertyBag["userMovies"] = _userMoviesLogic.GetMoviesByUSerAdvanced(id <= 0 ? User.Id : id, collectionId, mediaTypeId,
                                                                                 viewed, userMoviesStatusId, conditionId);

            SetFilterStrings(collectionId, mediaTypeId, viewed, userMoviesStatusId, conditionId);
        }

        private void BuildMoviePage(long id, long? movieId)
        {
            SetUser();
            SetPage(PageTypes.Movies);
            SetLayout(true);
            PropertyBag["CurrentUser"] = User.Id;
            PropertyBag["UserId"] = id == 0 ? User.Id : id;
            if (id <= 0 || id == User.Id)
                PropertyBag["Who"] = "My";
            else
                PropertyBag["Who"] = _userLogic.Find(id).UserName + "'s";

            if (movieId > 0)
            {
                PropertyBag["CollectionMovie"] = _userMoviesLogic.Find((long)movieId);
                PropertyBag["CreateCollection"] = true;
            }

            PropertyBag["ViewingUser"] = id <= 0 ? User.Id : id;
            
            ISubscriptions subscriptionsLogic = new SubscriptionsLogic();
            UserInfo currentUser = _userLogic.Find(User.Id);
            if (subscriptionsLogic.IsActiveService(currentUser, ExternalServices.Netflix) && !String.IsNullOrEmpty(currentUser.NetflixId))
                PropertyBag["IsNetflix"] = true;
            else
                PropertyBag["IsNetflix"] = false;
        }

        public void UserMoviesList(string letter, long id, long? movieId)
        {
            BuildMoviePage(id, movieId);
            GetUserMovies(letter, id);
        }

        private void GetUserMovies(string letter, long id)
        {
            var alphaStart = Char.Parse("A");
            var alphaEnd = Char.Parse("Z");
            StringBuilder sb = new StringBuilder();
            sb.Append(@"<li id='UserButton#'");
            if (letter != "#")
                sb.Append(@"class='notactive'");
            sb.Append(@" onclick=""window.location='UserMoviesList.ashx?id=" + (id <= 0 ? User.Id : id) + @"&letter=#'"">#</li>");
            for (var i = alphaStart; i <= alphaEnd; i++)
            {
                sb.Append(@"<li id='UserButton" + i + @"'");
                if (i.ToString() != letter)
                    sb.Append(@"class='notactive'");
                sb.Append(@" onclick=""window.location='UserMoviesList.ashx?id=" + (id <= 0 ? User.Id : id) + "&letter=" + i + @"'"">" + i + "</li>");
            }
            PropertyBag["Letters"] = sb.ToString();

            string let = "#";
            if (!string.IsNullOrEmpty(letter))
                let = letter;
            PropertyBag["userMovies"] = _userMoviesLogic.GetMoviesByFirstLetter(let, id <= 0 ? User.Id : id);
        }

        private void SetFilterStrings(long? collectionId, int? mediaTypeId, bool? viewed, int? userMoviesStatusId, int? conditionId)
        {
            string searchFilters = string.Empty;
            //string movieTypeString = id <= 0 ? string.Empty : "&id=" + id;
            //string collectionString = id <= 0 ? string.Empty : "&id=" + id;
            //string viewedString = id <= 0 ? string.Empty : "&id=" + id;

            string movieTypeString = string.Empty;
            string collectionString = string.Empty;
            string viewedString = string.Empty;
            string userMoviesStatusString = string.Empty;
            
            if (collectionId != null && collectionId > 0)
            {
                searchFilters += CreateFilter("collectionId", _userCollectionsLogic.Find(Convert.ToInt64(collectionId)).Name);
            }
            if (mediaTypeId != null && mediaTypeId > 0)
            {
                searchFilters += CreateFilter("mediaTypeId", _movieTypesLogic.Find(Convert.ToInt32(mediaTypeId)).Description);
            }
            if (viewed != null)
            {
                searchFilters += CreateFilter("viewed", viewed.ToString());
            }
            if (userMoviesStatusId != null && userMoviesStatusId > 0)
            {
                searchFilters += CreateFilter("userMoviesStatusId", _userMoviesStatusLogic.Find(Convert.ToInt32(userMoviesStatusId)).Name);
            }
            if (conditionId != null && conditionId > 0)
            {
                searchFilters += CreateFilter("conditionId", _userConditionLogic.Find(Convert.ToInt32(conditionId)).Name);
            }
            collectionString += "&mediaTypeId=" + mediaTypeId;
            collectionString += "&viewed=" + viewed;
            collectionString += "&userMoviesStatusId=" + userMoviesStatusId;
            movieTypeString += "&collectionId=" + collectionId;
            movieTypeString += "&viewed=" + viewed;
            movieTypeString += "&userMoviesStatusId=" + userMoviesStatusId;
            userMoviesStatusString += "&mediaTypeId=" + mediaTypeId;
            userMoviesStatusString += "&viewed=" + viewed;
            userMoviesStatusString += "&collectionId=" + collectionId;
            viewedString += "&mediaTypeId=" + mediaTypeId;
            viewedString += "&collectionId=" + collectionId;
            viewedString += "&userMoviesStatusId=" + userMoviesStatusId;

            PropertyBag["collectionString"] = collectionString;
            PropertyBag["movieTypeString"] = movieTypeString;
            PropertyBag["viewedString"] = viewedString;
            PropertyBag["userMoviesStatusString"] = userMoviesStatusString;
            if (searchFilters.Length > 0)
                PropertyBag["SearchFilters"] = @"<div class=""Breadcrumbs""><div class=""BreadCrumbHolder""><div class=""BreadCrumbHeader""><h4>Filters</h4><br /> <span>(click to remove)<span></div>" + searchFilters + "</div></div>";
        }

        #endregion
        
        #region Collections

        public void AddCollection()
        {
            SetUser();
            
        }

        public void SaveNewCollection(string name)
        {
            SetUser();
            UserInfo userInfo = _userLogic.Find(User.Id);

            var userCollections = new UserCollections(name);
            userCollections.UserInfo = userInfo;
            userCollections.DateAdded = DateTime.Now;
            userCollections.DateAddedBy = userInfo;
            userCollections.LastModified = DateTime.Now;
            userCollections.LastModifiedBy = userInfo;
            _userCollectionsLogic.Create(userCollections);

            RenderText(userCollections.Id.ToString());
        }

        #endregion
        
        #region Detail

        public void SetToView(long userMovieId)
        {
            SetUser();
            UserMovies userMovies = _userMoviesLogic.Find(userMovieId);
            if (userMovies.UserInfo.Id != User.Id)
                throw new Exception("You cannont edit a movie that is not your own.");
            userMovies.Viewed = true;
            userMovies.LastModified = DateTime.Now;
            userMovies.LastModifiedBy = _userLogic.Find(User.Id);
            userMovies.FriendMovieRequests = new List<FriendMovieRequest>();
            try
            {
                _userMoviesLogic.Update(userMovies);
            }
            catch (Exception ex)
            {
                RenderText(ex.Message);
                return;
            }
            RenderText("Successful");
        }

        public void RemoveMovie(long userMovieId)
        {
            SetUser();
            UserMovies userMovies = _userMoviesLogic.Find(userMovieId);
            if (userMovies.UserInfo.Id != User.Id)
                throw new Exception("You cannont delete a movie that is not your own.");
            string movieName = userMovies.Name;

            if (userMovies.FriendMovieRequests != null && userMovies.FriendMovieRequests.Count > 0)
            {
                IFriendMovieRequest movieRequestLogic = new FriendMovieRequestLogic();
                foreach (var movieRequest in userMovies.FriendMovieRequests)
                {
                    movieRequestLogic.Delete(movieRequest);
                }
            }
            userMovies.FriendMovieRequests = new List<FriendMovieRequest>();
            _userMoviesLogic.Delete(userMovies);

            _userActivityLogic.Create(new UserActivity(_userLogic.Find(User.Id), "removed " + movieName, DateTime.Now, (int)UserActivityTypes.RemoveMovie, userMovieId));

            RenderText(movieName);
        }

        public void EditMovie(long userMovieId)
        {
            SetUser();
            SetPage(PageTypes.Movies);
            SetLayout(true);

            UserMovies userMovies = _userMoviesLogic.Find(userMovieId);
            if (userMovies.UserInfo.Id == User.Id)
                PropertyBag["UserMovie"] = userMovies;
            else
                throw new Exception("You cannont edit a movie that is not your own.");

            PropertyBag["MovieType"] = _movieTypesLogic.FindAll();
            ICondition condition = new ConditionLogic();
            PropertyBag["Conditions"] = condition.FindAll();
            PropertyBag["UserCollections"] = _userCollectionsLogic.GetUserCollectionsByUser(User.Id);
            PropertyBag["UserMoviesStatuses"] = _userMoviesStatusLogic.FindAll();
            
        }

        public void SaveEdit([DataBind("UserMovie")] UserMovies UserMovie)
        {
            SetUser();
            UserMovies saveMovie = _userMoviesLogic.Find(UserMovie.Id);
            UserInfo userInfo = _userLogic.Find(User.Id);

            //if (UserMovie.Movie != null)
            //    saveMovie.Movie = _movieLogic.Find(UserMovie.Movie.Id);

            saveMovie.AdditionalInfo = HttpUtility.HtmlEncode(UserMovie.AdditionalInfo);
            ICondition condition = new ConditionLogic();
            saveMovie.Condition = condition.Find(UserMovie.Condition.Id);
            saveMovie.UserMoviesStatus = _userMoviesStatusLogic.Find(UserMovie.UserMoviesStatus.Id);
            saveMovie.Location = UserMovie.Location;
            saveMovie.MovieTypes = _movieTypesLogic.Find(UserMovie.MovieTypes.Id);
            saveMovie.UserCollections = _userCollectionsLogic.Find(UserMovie.UserCollections.Id);
            saveMovie.Viewed = UserMovie.Viewed;
            saveMovie.Name = UserMovie.Name;
            saveMovie.Notes = string.IsNullOrEmpty(UserMovie.Notes) ? HttpUtility.HtmlEncode(UserMovie.Notes) : string.Empty;
            if (saveMovie.Notes == null)
                saveMovie.Notes = "";
            saveMovie.FriendMovieRequests = new List<FriendMovieRequest>();
            
            saveMovie.LastModified = DateTime.Now;
            saveMovie.LastModifiedBy = userInfo;

            _userMoviesLogic.Update(saveMovie);

            var query = new NameValueCollection();
            query.Add("id", UserMovie.Id.ToString());
            query.Add("UserId", User.Id.ToString());
            Redirect("Movie","Detail",query);
        }
        
        public void Detail(long id, long userId)
        {
            SetUser();
            SetPage(PageTypes.Movies);
            SetLayout(true);
            PropertyBag["CurrentUser"] = User.Id;
            PropertyBag["IsAdmin"] = _userLogic.Find(User.Id).IsAdmin;
            PropertyBag["ViewingUser"] = userId <= 0 ? User.Id : userId;

            UserMovies userMovies = _userMoviesLogic.Find(id);
            IList<UserMovies> movieChildren = _userMoviesLogic.GetMovieChildren(id);
            if (!String.IsNullOrEmpty(userMovies.AdditionalInfo))
                userMovies.AdditionalInfo = userMovies.AdditionalInfo.Replace("\r", "<br />");
            PropertyBag["UserMovie"] = userMovies;
            PropertyBag["MovieChildren"] = movieChildren;
            if (userId > 0)
                PropertyBag["IsUser"] = userId == User.Id;
            else
                PropertyBag["IsUser"] = userMovies.UserInfo.Id == User.Id;

            try
            {
                if (userMovies.Movie != null && userMovies.Movie.Id > 0)
                    RunAmazon(userMovies.Movie);
            }
            catch (Exception)
            {
                //TODO: Handle Amazon exceptions ... especially too big of a request
            }
            
            IComments commentsLogic = new CommentsLogic();
            IList<Comments> allcomments = commentsLogic.GetCommentsByUserMovie(id);
            var sb = new StringBuilder();
            if (allcomments.Count > 0)
            {
                foreach (var comments in allcomments)
                {
                    sb.Append(CommentsHelper.BuildSmallComment(comments, true));
                }
            }
            PropertyBag["Comments"] = sb.ToString();
        }

        private void SetServices(ServicesMovieLink servicesMovieLink)
        {
            if (servicesMovieLink != null)
            {
                if (servicesMovieLink.ImdbId != null)
                    PropertyBag["IMDBScript"] = "RunIMDB('" + servicesMovieLink.ImdbId + "');";
                if (servicesMovieLink.AmazonId != null)
                    PropertyBag["AmazonScript"] = "RunAmazon('" + servicesMovieLink.AmazonId + "');";
                if (servicesMovieLink.NetflixId != null)
                    PropertyBag["NetflixScript"] = "RunNetflix('" + servicesMovieLink.NetflixId + "');";
            }
        }

        public void RodunuMovie(long id)
        {
            SetUser();
            SetPage(PageTypes.Movies);
            SetLayout(true);
            PropertyBag["CurrentUser"] = User.Id;
            PropertyBag["IsAdmin"] = _userLogic.Find(User.Id).IsAdmin;
            PropertyBag["ViewingUser"] = User.Id;

            Movie movie = _movieLogic.Find(id);

            RunAmazon(movie);

            PropertyBag["Movie"] = movie;
        }

        #endregion

        #region Import Code (Unused)

        public void ImportFromExcel()
        {
            SetPage(PageTypes.Movies);
            SetLayout(true);
        }

        private string _fileLocation = @"c:\TempMovieSpreadsheets\";

        public void GetExcelFile(HttpPostedFile file)
        {
            if (file.ContentType == "application/vnd.ms-excel" ||
                file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                file.SaveAs(_fileLocation + file.FileName);

                var importFromExcel = new ImportFromExcel();
                IList<string> sheets = importFromExcel.GetExcelSheets(_fileLocation + file.FileName);

                sheets.Insert(0, file.FileName);
                PropertyBag["Sheets"] = JavaScriptConvert.SerializeObject(sheets);
            }
            else
                RenderText(file.ContentType);

        }

        public void RunExport(string fileName, string sheet)
        {
            var importFromExcel = new ImportFromExcel();
            PropertyBag["headers"] = importFromExcel.GetRowHeaders(sheet, _fileLocation + fileName);
            PropertyBag["sheet"] = sheet;
            PropertyBag["fileName"] = fileName;
        }

        public void StartExport(string fileName, string sheet, string movieName, string typeName, string viewedName, int viewedType, string collectionName, string pageName)
        {
            var importFromExcel = new ImportFromExcel(_fileLocation + fileName, sheet);
            if (HttpUtility.UrlDecode(collectionName) != "No Column")
                importFromExcel.CollectionVariable = collectionName;
            importFromExcel.MovieVariable = movieName;
            if (HttpUtility.UrlDecode(pageName) != "No Column")
                importFromExcel.PageVariable = pageName;
            if (HttpUtility.UrlDecode(typeName) != "No Column")
                importFromExcel.TypeVariable = typeName;
            if (viewedType > 0)
                importFromExcel.ViewedType = (ViewedTypes)viewedType;
            else
                importFromExcel.ViewedType = null;
            if (HttpUtility.UrlDecode(viewedName) != "No Column")
                importFromExcel.ViewedVariable = viewedName;
            
            importFromExcel.Read();

            //IList<ImportMovie> movies = importFromExcel.Movies;
            //foreach (var movie in movies)
            //{
            //    movie.MovieName = HttpUtility.HtmlEncode(movie.MovieName);
            //}
            PropertyBag["Movies"] = importFromExcel.Movies;
        }

        #endregion

        #region Private Methods

        private string CreateFilter(string id, string name)
        {
            var filter = new StringBuilder();
            filter.Append(@"<div class=""Breadcrumb"" onclick=""ClearThisCrumb(this,'");
            filter.Append(id);
            filter.Append(@"')"">");
            filter.Append(name);
            filter.Append("</div>");
            return filter.ToString();
        }

        #endregion

        #region Amazon

        public void AmazonDetail(long id, long userId, long movieId)
        {
            SetUser();
            SetPage(PageTypes.Movies);
            SetLayout(true);
            PropertyBag["CurrentUser"] = User.Id;
            PropertyBag["IsAdmin"] = _userLogic.Find(User.Id).IsAdmin;
            PropertyBag["ViewingUser"] = userId <= 0 ? User.Id : userId;
            
            if (id > 0)
            {
                UserMovies userMovies = _userMoviesLogic.Find(id);
                PropertyBag["UserMovie"] = userMovies;

                if (userId > 0)
                    PropertyBag["IsUser"] = userId == User.Id;
                else
                    PropertyBag["IsUser"] = userMovies.UserInfo.Id == User.Id;

                try
                {
                    if (userMovies.Movie != null && userMovies.Movie.Id > 0)
                        RunAmazon(userMovies.Movie);
                }
                catch (Exception)
                {
                    //TODO: Handle Amazon exceptions ... especially too big of a request
                }
            }
            else if (movieId > 0)
            {
                PropertyBag["IsUser"] = userId == User.Id;

                Movie movie = _movieLogic.Find(movieId);
                PropertyBag["Movie"] = movie;

                if (movie != null && movie.Id > 0)
                    RunAmazon(movie);
            }

        }

        private void RunAmazon(Movie movie)
        {
            IAmazonService amazonService = new AmazonService();
            if (String.IsNullOrEmpty(movie.AmazonASIN))
            {
                if (movie.Upc > 0)
                {
                    //Load Amazon data if possible
                    AmazonSearchResult amazonSearchResult = amazonService.SearchWebService(movie.Upc.ToString(), 0, 1,
                                                                                           true, true);
                    if (amazonSearchResult.Titles.Count == 1)
                    {
                        //UserInfo userInfo = _userLogic.Find(User.Id);
                        Title title = amazonSearchResult.Titles.First();
                        PropertyBag["AmazonMovie"] = title;
                        movie.AmazonASIN = title.AmazonASIN;
                        movie.LargeImageUrl = title.LargeImageUrl;
                        movie.SmallImageUrl = title.SmallImageUrl;
                        movie.LastModified = DateTime.Now;
                        movie.UserMovies = new List<UserMovies>();
                        //movie.
                        _movieLogic.Update(movie);
                    }
                }
            }
            else
            {
                //TODO Try by title
                var title = amazonService.GetAmazonTitleByASIN(movie.AmazonASIN);
                PropertyBag["AmazonMovie"] = title;
                movie.AmazonASIN = title.AmazonASIN;
                movie.LargeImageUrl = title.LargeImageUrl;
                movie.SmallImageUrl = title.SmallImageUrl;
                movie.LastModified = DateTime.Now;
                movie.UserMovies = new List<UserMovies>();
                _movieLogic.Update(movie);
            }

            string movieName = movie.Name;
            if (movie.Name.IndexOf("(") > 0)
            {
                movieName = movieName.Substring(0, movie.Name.IndexOf("("));
            }
            movieName = movieName.Replace(":", "");
            //try
            //{
            //    AmazonSearchResult movies = amazonService.SearchWebService(movieName, 0, 1, true, false);
            //    PropertyBag["AmazonMovies"] = movies.Titles;
            //}
            //catch (Exception)
            //{

            //}
        }

        public void MakeDefaultAmazon(long movieId, string amazonASIN)
        {
            SetUser();
            Movie movie = _movieLogic.Find(movieId);

            IAmazonService amazonService = new AmazonService();
            var title = amazonService.GetAmazonTitleByASIN(amazonASIN);
            movie.AmazonASIN = amazonASIN;
            movie.LargeImageUrl = title.LargeImageUrl;
            movie.SmallImageUrl = title.SmallImageUrl;
            movie.LastModified = DateTime.Now;
            movie.UserMovies = new List<UserMovies>();
            _movieLogic.Update(movie);

            RenderText("1");
        }

        #endregion

        public void LinkMovieToMovie(int userMovieId, int movieId)
        {
            SetUser();
            UserMovies userMovies = _userMoviesLogic.Find(userMovieId);
            if (userMovies.UserInfo.Id != User.Id)
                throw new Exception("You cannont link a movie that is not your own.");

            _userMoviesLogic.LinkMovieToUserMovie(movieId, userMovieId);
            
            var query = new NameValueCollection();
            query.Add("id", userMovieId.ToString());
            query.Add("UserId", User.Id.ToString());
            Redirect("Movie", "Detail", query);
            Redirect("Movie", "Detail", query);
        }
    }
}
